<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="!crud.props.searchToggle">
        <el-form size="small" label-width="100px" :rules="rules" ref="form" :model="crud.order"
                 :disabled="pageDisabled"
        >
          <!--          第一行-->
          <el-row :gutter="10">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="业务日期">
                <el-date-picker
                  v-model="crud.order.busDate"
                  type="date"
                  size="small"
                  :disabled="crud.order.orderStatus==='PASS'"
                  class="date-item"
                  style="width: 100%;"
                  format="yyyy - MM - dd"
                  value-format="yyyy-MM-dd"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="单据编号">
                <el-input v-model="crud.order.code" readonly placeholder="系统自动生成"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="状态">
                <el-input v-model="orderStatusLabel" readonly/>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="客户">
                <zSelect :value.sync="crud.order.customerId" :showName="crud.order.customerName" @change="customerIdChange"
                         url="api/dropDown/basCustomerList" :params="{businessAttr:'3'}" style="width:  100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <!--          第二行-->
          <el-row :gutter="10">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="销售部门">
                <zSelect :value.sync="crud.order.deptId" :showName="crud.order.deptName"
                         url="api/dropDown/childSysDeptList" style="width:  100%"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="业务员">
                <zSelect :value.sync="crud.order.userId" :showName="crud.order.userName"
                         url="api/dropDown/sysUserList" style="width:  100%;"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="收款类型">
                <el-select v-model="crud.order.type" clearable placeholder="请选择" size="small"
                           style="width: 100%;"
                >
                  <el-option v-for="item in dict.t_finance_customer_receipt_type" :key="item.id" :label="item.label"
                             :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="客户编码">
                <el-input v-model="crud.order.customerCode" readonly></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <!--          第三行-->
          <el-row :gutter="10">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="收款总额">
                <el-input v-model="crud.order.taxAmount" readonly></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="已核销金额">
                <el-input v-model="crud.order.cancelAmount" readonly></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="未核销金额">
                <el-input v-model="crud.order.unCancelAmount" readonly></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="尾差">
                <el-input v-model="crud.order.tailAmount" readonly></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="抵扣金额">
                <el-input v-model="crud.order.deductionAmount"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="本次核销金额">
                <el-input v-model="crud.order.curCancelAmount" readonly></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="12" :xl="12">
              <el-form-item label="备注">
                <el-input v-model="crud.order.remark"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row gutter="10">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="总应收">
                <el-input v-model="crud.order.debtAmount" readonly :disabled="true"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="可分配金额">
                <el-input :value="getCanUseAmount" readonly :disabled="true"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="收款人">
                <zSelect :value.sync="crud.order.payeeUserId" :showName="crud.order.payeeUserName"
                         url="api/dropDown/sysUserList" style="width:  100%;"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="出纳">
                <zSelect :value.sync="crud.order.cashierUserId" :showName="crud.order.cashierUserName"
                         url="api/dropDown/sysUserList" style="width:  100%;"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <!--   操作栏   -->
      <div class="handler-div" >
        <div class="handler-div-left">
          <el-button
            slot="left"
            class="filter-item"
            @click="addDetail"
            type="primary"
            size="mini"
          >
            添加
          </el-button>
          <el-button slot="right" class="filter-item" :disabled="crud.order.orderStatus==='PASS'||pageDisabled"
                     size="mini"
                     type="primary" @click="submit()"
          >
            保存
          </el-button>
          <el-button slot="right" class="filter-item" size="mini" type="success"
                     :disabled="$route.params.id=='null'||pageDisabled"
                     :loading="crud.passLoading" @click="crud.doDetailPassOrReject('PASS',id)"
          >
            审核
          </el-button>
          <el-button slot="right" class="filter-item" size="mini" type="info" :loading="crud.rejectLoading"
                     :disabled="crud.order.orderStatus !== 'PASS'" @click="crud.doDetailPassOrReject('REJECT',id)"
          >
            反审
          </el-button>
          <el-button
            :loading="crud.downloadLoading"
            class="filter-item"
            size="mini"
            type="warning"
            @click="crud.preView"
            :disabled="$route.params.id == 'add'"
          >打印</el-button>
          <el-button
            :loading="crud.downloadLoading"
            class="filter-item"
            size="mini"
            type="warning"
            @click="crud.preView1"
            :disabled="$route.params.id == 'add'"
          >打印预览</el-button>
          <el-button
            class="filter-item"
            size="mini"
            type="warning"
            @click="crud.refresh()"
          >刷新</el-button>

          <el-button
            class="filter-item"
            size="mini"
            type="warning"
            v-permission="permission.refund"
            @click="onRefund"
          >线上退款</el-button>
<!--          <el-button slot="right" class="filter-item" size="mini" type="info" :loading="crud.rejectLoading"-->
<!--                     :disabled="$route.params.id=='null'||pageDisabled"-->
<!--          >-->
<!--            打印-->
<!--          </el-button>-->
<!--          <el-button slot="right" class="filter-item" size="mini" type="info" :loading="crud.rejectLoading"-->
<!--                     :disabled="$route.params.id=='null'||pageDisabled"-->
<!--          >-->
<!--            打印预览-->
<!--          </el-button>-->
        </div>
        <div class="handler-div-right">
          <el-button slot="right" class="filter-item" size="mini" type="info" :loading="crud.rejectLoading"
                     @click="addBankData" :disabled="pageDisabled"
          >
            添加银行
          </el-button>
        </div>
      </div>
      <el-dialog
        title="请选择打印模板"
        :visible.sync="crud.printConfig.pringDialog"
        width="30%"
        v-dialogDrag
      >
        <jPrintConfig groupId="financeCustomerReceipt"
                      v-if="crud.printConfig.pringDialog"
                      @getPrintId="crud.detailedPrint"
                      :isPreview="crud.printConfig.isPreview"
        ></jPrintConfig>
      </el-dialog>
      <el-table ref="bank-table" stripe border v-loading="crud.loading" :row-class-name="crud.tableRowClassName"
                :row-key="getRowKey"
                :data="bankData" size="small" style="width: 100%;" :show-summary="true" sortable="custom"
      >
        <el-table-column :render-header="crud.renderHeader" type="selection" width="60"/>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsCode')" prop="goodsCode"
                         label="银行"
        >
          <template slot-scope="{row,$index}">
            <zSelect :ref="'zSelect'+new Date().getTime()" :value.sync="row.bankId" :showName="row.bankName"
                     :disabled="pageDisabled"
                     url="api/dropDown/basBankList"
                     style="width:  100%;"
                     :params="{sort: 'seq desc'}"
                     data-total-key="data.length"  @change="bankSelectFunc"
                     @focus="bankSelectFocus(row,$index)"
            />
          </template>
        </el-table-column>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('bankOpenBranch')"
                         prop="bankOpenBranch" label="银行支行"
                         width="200"
        ></el-table-column>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('bankAccount')" prop="bankAccount"
                         label="银行账户"
        />
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('taxAmount')" prop="taxAmount"
                         label="金额"
        >
          <template slot-scope="{row}">
            <el-input v-model="row.taxAmount" @change="e=>bankTaxAmountChange(row)" :disabled="pageDisabled"></el-input>
          </template>
        </el-table-column>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('taxAmount')" prop="taxAmount"
                         label="未核销金额"
        >
          <template slot-scope="{row}">
            <el-input v-model="row.unCancelAmount" disabled></el-input>
          </template>
        </el-table-column>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('taxAmount')" prop="taxAmount"
                         label="已核销金额"
        >
          <template slot-scope="{row}">
            <el-input v-model="row.cancelAmount" disabled></el-input>
          </template>
        </el-table-column>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('remark')" prop="remark" label="备注"/>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('balanceAmount')" prop="balanceAmount"
                         label="账户余额"
        />
        <el-table-column :render-header="crud.renderHeader" label="操作" fixed="right" width="150px" align="center"
                         v-if="!pageDisabled">
          <template slot-scope="scope">
            <el-button slot="reference" class="el-icon-delete opration_icon_btn"
                       :disabled="crud.order.orderStatus==='PASS'" style="border: none;width: auto;height: auto"
                       @click="bankDelAddRow(scope.$index)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <hr style="margin: 20px 0">
      <div class="receipt-order">
        <el-button slot="right" class="filter-item" size="mini" type="info" @click="getFinanceCustomerReceiptOrder()"
                   :disabled="$route.params.id=='null'||pageDisabled"
        >
          申请抽单
        </el-button>
      </div>
      <el-table ref="table" stripe border v-loading="crud.loading" :row-class-name="crud.tableRowClassName"
                :data="crud.data" size="small" style="width: 100%;" :show-summary="true" sortable="custom"
                @sort-change="crud.sortChange" @selection-change="crud.selectionChangeHandler"
                @row-dblclick="crud.dbClick"
      >
        <el-table-column :render-header="crud.renderHeader" type="selection" width="60"/>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('busDate')" prop="busDate"
                         label="业务日期"
        />
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('sourceTypeName')"
                         prop="sourceTypeName" label="单据类型"
        ></el-table-column>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('sourceCode')" prop="sourceCode"
                         label="单据编号"
        />
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('customerCode')" prop="customerCode"
                         label="客户编码"
        />
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('customerName')" prop="customerName"
                         label="客户名称"
        />
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('taxAmount')" prop="taxAmount"
                         label="金额"
        />
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('cancelAmount')" prop="cancelAmount"
                         label="已核销金额"
        />
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('unCancelAmount')"
                         prop="unCancelAmount" label="未核销金额"
        />
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('curCancelAmount')"
                         prop="curCancelAmount" label="本次核销金额"
        >
          <template slot-scope="{row}">
            <el-input v-model="row.curCancelAmount" @change="curCancelAmountChange" :disabled="pageDisabled"></el-input>
          </template>
        </el-table-column>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('tailAmount')" prop="tailAmount"
                         label="尾差"
        >
          <template slot-scope="{row}">
            <el-input v-model="row.tailAmount" @change="residueAmountChange" :disabled="pageDisabled"></el-input>
          </template>
        </el-table-column>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('remark')" prop="remark" label="备注"/>
        <el-table-column :render-header="crud.renderHeader" label="操作" fixed="right" width="150px" align="center"
                         v-if="!pageDisabled">
          <template slot-scope="scope">
            <el-button slot="reference" class="el-icon-delete opration_icon_btn"
                       :disabled="crud.order.orderStatus==='PASS'" style="border: none;width: auto;height: auto"
                       @click="delAddRow(scope.$index)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination/>
    </div>
    <el-dialog title="申请抽单" :visible.sync="showReceiptOrder" width="80%">
      <div>
        <el-form size="small" label-width="100px" :model="receiptOrderQuery">
          <el-row :gutter="10">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="单据编号">
                <el-input v-model="receiptOrderQuery.sourceCode" placeholder="支持模糊查询"></el-input>
              </el-form-item>
            </el-col>

            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="单据类型">
                <el-select v-model="receiptOrderQuery.type" class="filter-item" clearable placeholder="状态" size="small"
                           style="width: 100%;"
                >
                  <el-option v-for="item in dict.receipt_payment_source" :key="item.id" :label="item.label"
                             :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="备注">
                <el-input v-model="receiptOrderQuery.remark" placeholder="单行输入"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="客户">
                <el-input v-model="receiptOrderQuery.customerKeyword" placeholder="单行输入"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-button type="primary" @click="receiptOrderSizeChangeHandler()">搜索</el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <el-table ref="table" stripe border :row-class-name="crud.tableRowClassName" v-loading="receiptOrderLoading"
                :data="receiptOrderTableData" size="small" style="width: 100%;"
                @selection-change="receiptOrderSelection"
                height="500"
      >
        <el-table-column :render-header="crud.renderHeader" type="selection" width="60"/>
        <el-table-column :render-header="crud.renderHeader" sortable v-if="columns.visible('busDate')" prop="busDate"
                         label="业务日期"
                         sortable
        />
        <el-table-column :render-header="crud.renderHeader" sortable v-if="columns.visible('sourceTypeName')"
                         prop="sourceTypeName"
                         label="单据类型"
        >
        </el-table-column>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('sourceCode')" prop="sourceCode"
                         label="单据编号"
                         sortable
        />
        <el-table-column :render-header="crud.renderHeader" sortable v-if="columns.visible('customerCode')" prop="customerCode"
                         label="客户编码"
        />
        <el-table-column :render-header="crud.renderHeader" sortable v-if="columns.visible('customerName')" prop="customerName"
                         label="客户名称"
        />
        <el-table-column :render-header="crud.renderHeader" sortable v-if="columns.visible('loadCode')" prop="loadCode"
                         label="配送单号"
                         sortable
        />
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('taxAmount')" prop="taxAmount"
                         label="金额"
                         sortable
        />
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('cancelAmount')" prop="cancelAmount"
                         label="已核销金额"
                         sortable
        />
        <el-table-column :render-header="crud.renderHeader" sortable v-if="columns.visible('unCancelAmount')"
                         prop="unCancelAmount" label="未核销金额"
        />
        <el-table-column :render-header="crud.renderHeader" sortable v-if="columns.visible('curCancelAmount')"
                         prop="curCancelAmount" label="本次核销金额"
        />
        <el-table-column :render-header="crud.renderHeader" sortable v-if="columns.visible('goodsCode')" prop="goodsCode"
                         label="尾差"
        />
        <el-table-column :render-header="crud.renderHeader" sortable v-if="columns.visible('remark')" prop="remark" label="备注"/>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="showReceiptOrder = false">取消</el-button>
        <el-button :loading="crud.cu === 2" type="primary" @click="receiptOrderConfirm">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import crudFinanceCustomerReceipt from '@/api/erp/financeCustomerReceipt';
import CRUD, {presenter, header, form, crud} from '@crud/crud';
import rrOperation from '@crud/RR.operation';
import crudOperation from '@crud/CRUD.operation';
import udOperation from '@crud/UD.operation';
import pagination from '@crud/Pagination';
import jtgSelectPlus from '@/components/select/JtgSelectPlus';
import {Notification, Pagination} from 'element-ui';
import {getFinanceCustomerReceiptOrder} from '@/api/erp/financeCustomerReceiptOrder';
import jPrintConfig from '@/components/jPrintConfig/jPrintConfig'
import { getJuniorDebt, refund } from '../../../api/erp/financeCustomerReceipt'
import {getSupplierPay} from "../../../api/erp/financeSupplierPayment";
import { trim } from '../../../../public/UEditor/third-party/xss.min'
// crud交由presenter持有
const defaultCrud = CRUD({
  title: '采购协议明细',
  params() {
    const href = location.href.split('/');
    return {
      id: href[href.length - 1] == 'add' ? 0 : href[href.length - 1]
    };
  },
  url: 'api/financeCustomerReceipt/detail', sort: 'id,desc', crudMethod: {...crudFinanceCustomerReceipt}
});
export default {
  name: 'financeCustomerReceiptDetail',
  components: {pagination, crudOperation, rrOperation, udOperation, jtgSelectPlus, 'el-pagination': Pagination, jPrintConfig},
  mixins: [presenter(defaultCrud), header(), crud()],
  dicts: ['t_finance_customer_receipt_type', 'receipt_payment_source', 'common_order_status'],
  // filters: {
  //   sourceTypeFilter(val, list) {
  //     const item = list.find(el => el.value === val * 1);
  //     if (item) {
  //       return item.label;
  //     } else {
  //       return '-';
  //     }
  //   }
  // },
  data() {
    return {
      getRowKey(row) {
        return row.bankKeyFlag;
      },
      debtAmount: 0,
      id: null,
      copyFrom: null,
      showReceiptOrder: false,
      permission: {
        add: ['admin', 'buyProtocolDetail:add'],
        edit: ['admin', 'buyProtocolDetail:edit'],
        del: ['admin', 'buyProtocolDetail:del'],
        import: ['admin', 'buyProtocolDetail:import'],
        export: ['admin', 'buyProtocolDetail:export'],
        copy: ['admin', 'buyProtocolDetail:copy'],
        upload: ['admin', 'buyProtocolDetail:upload'],
        download: ['admin', 'buyProtocolDetail:download'],
        refund: ['admin', 'financeCustomerReceipt:refund']
      },
      rules: {
        endDate: [
          {required: true, message: '结束日期不能为空', trigger: 'blur'}
        ],
        startDate: [
          {required: true, message: '开始日期不能为空', trigger: 'blur'}
        ],
        contactName: [
          {required: true, message: '联系人不能为空', trigger: 'blur'}
        ],
        customerId: [
          {required: true, message: '供应商不能为空', trigger: 'blur'}
        ],
        userId: [
          {required: true, message: '业务员不能为空', trigger: 'blur'}
        ],
        name: [
          {required: true, message: '协议不能为空', trigger: 'blur'}
        ],
        buyChannel: [
          {required: true, message: '采购渠道不能为空', trigger: 'blur'}
        ]
      },
      productList: [],
      bankData: [],// 银行数据,
      receiptOrderQuery: {},// 收款单单据查询条件
      receiptOrderPage: {
        // 页码
        page: 1,
        // 每页数据条数
        size: 999,
        // 总数据条数
        total: 0
      },  // 收款单单据翻页
      receiptOrderSelectData: [],// 选中的收款单单据明细
      receiptOrderTableData: [],// 收款单单据明细
      receiptOrderLoading: false, // 收款单弹窗loading
      bankFocusedIdx: 0, // 银行选中的某行
      taxAmount: 0, // 收款总金额汇总
      curCancelAmount: 0, // 本次核销金额
      cancelAmount: 0, // 已经核销金额
      tailAmount: 0 // 尾差
    };
  },
  computed: {
    getCanUseAmount(){
      //获取可分配金额=银行列表总金额-（抽单）（总本次核销金额+总尾差）
      return (this.getDataSummary(this.bankData, 'taxAmount') - (this.getDataSummary(this.crud.data, 'curCancelAmount') )).toFixed(6)
    },
    // 未核销金额 = 收款总金额 - 已经核销金额
    unwriteOffedAmount() {
      return (this.crud.order.taxAmount || 0) - (this.crud.order.cancelAmount || 0);
    },
    orderStatusLabel() {
      const status = this.crud.order.orderStatus;
      const common_order_status = this.dict.common_order_status;
      if (common_order_status.length > 0 && status) {
        return common_order_status.find(el => el.value === status).label;
      } else {
        return '';
      }
    },
    pageDisabled() {
      const status = this.crud.order.orderStatus;
      return ['CLOSE', 'PASS'].includes(status)
    }
  },
  created () {
    //获取屏幕高度
    let screenHeight = document.documentElement.clientHeight  + "px";
    this.$nextTick(() => {
      this.Height = screenHeight;
    })
  },

  activated() {
    //获取上次进入Id
    const id = sessionStorage.getItem(this.$options.name + 'Id')
    //记录本次进入的Id
    sessionStorage.setItem(this.$options.name+'Id',this.$route.params.id)
    if(id !== this.$route.params.id){
      if(this.$route.params.id === 'add'){
        console.log(this.copyFrom)
        this.$set(this.crud,'order',Object.assign({},this.copyFrom))
        this.$set(this.crud,'data',[])
        console.log(this.crud.data)
        this.$set(this,'bankData',[])
        console.log(this.bankData)
      }else if(this.$route.params.id.indexOf('copy') !== -1){
        const copyId = this.$route.params.id.split('=')[1]
        this.crud.toGetCopyInfo(copyId)
      }else {
        this.crud.params.id = this.$route.params.id
        this.crud.refresh()
      }
    }
  },
  mounted() {
    window.addEventListener('resize',this.onresize)
    // this.elTableHeight = $('.table-container').height();
    // const that = this;
    // window.onresize = () => {
    //   return (() => {
    //     let screenHeight = document.documentElement.clientHeight  + "px";
    //     that.Height = screenHeight;
    //   })()
    // };
    // if (this.$route.params.id == 'add') {
    //   if (this.crud.getItemInfo('financeCustomerReceiptDetail_add')) {
    //     if (this.crud.order.hasOwnProperty('bankList')) this.bankData = this.crud.order.bankList
    //     return false;
    //   }
      // this.elTableHeight = $('.table-container').height();
      this.crud.order = Object.assign({
        id: null,
        code: '',
        butDate: new Date().toISOString().split('T')[0],
        name: '',
        userId: '',
        orderStatus: 'SAVE',
        index: '0',
        buyChannel: null,
        customerId: '',
        contactName: '',
        contactPhone: '',
        startDate: null,
        endDate: null,
        remark: '',
        type: 1,
        debtAmount: null,
        payeeUserId: '',
        cashierUserId: ''
      })
      this.copyFrom = Object.assign({}, this.crud.order)
    // }

  },
  beforeUpdate() {
    if (this.$route.params.id != 'add') {
      this.id = this.$route.params.id;
      this.crud.order.id = this.id;
    }
  },
  methods: {


    getTime(date = new Date()) {
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      m = m < 10 ? ('0' + m) : m;
      var d = date.getDate();
      d = d < 10 ? ('0' + d) : d;
      var h = date.getHours();
      h = h < 10 ? ('0' + h) : h;
      var minute = date.getMinutes();
      minute = minute < 10 ? ('0' + minute) : minute;
      var second = date.getSeconds();
      second = second < 10 ? ('0' + second) : second;
      // +' '+h+':'+minute+':'+second;
      return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
    },
    delAddRow(i) {
      if (this.$route.params.id !== 'add') {
        this.$confirm('此操作将直接删除此条抽单记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.crud.data.splice(i, 1);
          // 重新计算尾差和本次核销金额
          this.curCancelAmountChange();
          this.residueAmountChange();
          this.bankTaxAmountChange();
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      } else {
        this.crud.data.splice(i, 1);
        // 重新计算尾差和本次核销金额
        this.curCancelAmountChange();
        this.residueAmountChange();
        this.bankTaxAmountChange();
      }
    },
    onRefund(){
      this.$prompt('请输入退款原因', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({ value }) => {
        if (!value)return this.$message.error('退款原因必输')
        console.log(value)
        refund({refundReason:value,orderId:this.crud.order.id,payType:this.crud.order.payType}).then(res=>{
          if (res.status === 200){
            this.$message.success('退款成功')
          }
          else {
            this.$message.error(res.msg)
          }
        }).catch(err=>this.$message.error(err.msg))
      })
    },
    // 删除银行
    bankDelAddRow(i) {
      this.bankData.splice(i, 1);
      // 重新计算尾差和本次核销金额
      this.curCancelAmountChange();
      this.residueAmountChange();
      this.bankTaxAmountChange();
      this.$forceUpdate();
    },
    // 保存
    submit() {
      this.save();
    },
    tableRules(index, name, value) {
      if (!value) {
        Notification.error({title: '序号【' + index + '】' + name + '不能为空'});
        return false;
      } else {
        return true;
      }
    },
    onresize(e){
      console.log(e)
      console.log(window.devicePixelRatio)
      const app = document.getElementsByClassName('el-form')[0]
      console.log(app.offsetTop)
    },
    //保存
    save() {
      let that = this;
      this.crud.order.bankList = this.bankData;
      this.crud.order.orderList = this.crud.data;
      let params = this.crud.order;
      params.unCancelAmount = this.unwriteOffedAmount;
      if (this.checkParams(params)) {
        Notification.error({title: '请先选择客户'});
        return;
      }
      that.crud.loadingOpen();
      crudFinanceCustomerReceipt.add(params).then(res => {
        if (res.success) {
          const {financeCustomerReceiptBankList, financeCustomerReceiptDto, financeCustomerReceiptOrderList} = res.data;
          this.bankData = financeCustomerReceiptBankList || [];
          this.crud.order = financeCustomerReceiptDto || {};
          this.crud.data = financeCustomerReceiptOrderList || [];
          // this.crud.order = res.data;
          // this.crud.data = res.data.detailList
          let id = this.crud.order.id;

          if (this.$route.params.id == 'add') {
            this.$router.replace('/redirect/finance/financeCustomerReceiptDetail/'+id)
          }
          this.$message({
            message: '保存成功',
            type: 'success'
          });
          that.crud.loadingClose();
        } else {
          that.crud.loadingClose();
          this.$message({
            message: res.msg,
            type: 'warning'
          });
        }

      }).catch((res) => {
        that.crud.loadingClose();
      });
    },
    // 必填参数校验
    checkParams(params) {
      const {customerId} = params;
      // 后续可以其他参数校验可以在这里增加
      return !customerId;
    },
    // 获取数据前设置好接口地址
    [CRUD.HOOK.beforeRefresh]() {
      return true;
    }, // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
    },
    [CRUD.HOOK.afterRefresh](crud, data) {
      if (this.$route.params.id !== 'add') {
        const {financeCustomerReceiptBankList, financeCustomerReceiptDto, financeCustomerReceiptOrderList} = data;
        this.bankData = financeCustomerReceiptBankList || [];
        this.crud.order = financeCustomerReceiptDto || {};
        this.crud.data = financeCustomerReceiptOrderList || [];
      }
    },
    // 添加银行数据
    addBankData() {
      // if (!this.crud.order.customerId) {
      //   this.$message({
      //     type: 'warning',
      //     message: '请先选择客户'
      //   })
      // } else {
      let bankItem = {
        bankKeyFlag: 'bankKeyFlag-' + new Date().getTime(),
        bankId: '',
        bankName: '',
        bankOpenBranch: '',
        bankAccount: '',
        balanceAmount: '',
        taxAmount: '',
        remark: '',
        cancelAmount: 0,
        unCancelAmount: 0
      };
      this.bankData.push(bankItem);
      // }
    },
    // 选择银行之后
    bankSelectFunc(selectedBank) {
      const {id, name, bankOpenBranch, bankAccount, balanceAmount, remark} = selectedBank;
      const idx = this.bankFocusedIdx;
      if (idx >= 0) {
        const {taxAmount, bankKeyFlag} = JSON.parse(JSON.stringify(this.bankData[idx]));
        this.bankData.splice(idx, 1, {
          bankKeyFlag,
          bankId:id,
          bankName:name,
          bankOpenBranch,
          bankAccount,
          balanceAmount,
          taxAmount,
          remark,
          cancelAmount: 0,
          unCancelAmount: 0,
        });
      }
    },
    // 银行数据中当前选中的某行
    bankSelectFocus(row, idx) {
      this.bankFocusedIdx = idx;
    },
    // 选中收款单单据
    receiptOrderSelection(selectedList) {
      this.receiptOrderSelectData = selectedList;
    },
    // 弹窗页条数点击
    receiptOrderSizeChangeHandler(e) {
      this.receiptOrderPage.page = 1;
      this.getFinanceCustomerReceiptOrder();
    },
    // 弹窗翻页点击
    receiptOrderPageChangeHandler(e) {
      this.receiptOrderPage.page = e;
      this.getFinanceCustomerReceiptOrder();
    },
    // 收款单单据弹窗点击确定
    receiptOrderConfirm(e) {
      if (!this.crud.data) this.crud.data = [];
      const orderListSourceCodeList = this.crud.data.map(item=>item.sourceCode)
      let newList = JSON.parse(JSON.stringify(this.receiptOrderSelectData))
      for(let i of newList){
        if (orderListSourceCodeList.includes(i.sourceCode)){
          this.$message.error(`单据编号${i.sourceCode}已存在，请核查！`)
          return
        }
        i.curCancelAmount = i.unCancelAmount
      }
      // newList.forEach(el =>
      //   el.curCancelAmount = el.unCancelAmount
      // );


      this.crud.data.push(...newList);
      this.showReceiptOrder = false;
      // 重新计算尾差和本次核销金额
      this.curCancelAmountChange();
      this.residueAmountChange();
      this.bankTaxAmountChange();
    },
    // 收款单单据列表
    getFinanceCustomerReceiptOrder() {
      if (!this.crud.order.customerId) {
        this.$message({
          type: 'warning',
          message: '请先选择客户'
        });
      } else {
        let params = {
          ...this.receiptOrderPage,
          ...this.receiptOrderQuery
        };
        this.receiptOrderLoading = true;
        params.customerId = this.crud.order.customerId;
        getFinanceCustomerReceiptOrder(params).then(res => {
          this.receiptOrderTableData = res.data.content;
          this.showReceiptOrder = true;
          this.receiptOrderLoading = false;
          this.receiptOrderPage.total = res.data.totalElements;
        }).finally(() => {
          this.receiptOrderLoading = false;
        });
      }
    },
    // 获取合计值
    getDataSummary(list = [], key) {
      let total = 0;
      list.forEach(el => total += (el[key] * 1));
      return total.toFixed(2);
    },
    addDetail(){
      // if (this.detailName === 'salesOrder_add'){
      //   this.$message({
      //     type:'error',
      //     message: '当前已在添加界面'
      //   })
      // }
      if(this.$route.params.id !== 'add')
      this.$router.replace({ path: '/redirect/finance/financeCustomerReceiptDetail/add' })
    },
    // 银行金额变化
    bankTaxAmountChange(row) {
      console.log(row)
      this.$set(this.crud.order, 'taxAmount', this.getDataSummary(this.bankData, 'taxAmount'));
      this.$set(row,'unCancelAmount',Number(row.taxAmount || 0) - Number(row.cancelAmount) || 0)
    },
    // 银行金额变化
    curCancelAmountChange() {
      this.$set(this.crud.order, 'curCancelAmount', this.getDataSummary(this.crud.data, 'curCancelAmount'));
    },
    // 尾差汇总
    residueAmountChange() {
      this.$set(this.crud.order, 'tailAmount', this.getDataSummary(this.crud.data, 'tailAmount'));
    },
    // 客户选择后
    customerIdChange(item) {
      console.log('itemitemitemitemitem', item)
      const {name, deptId, deptName, userId, userName, code, debtAmount} = item;
      // this.crud.order.juniorDebt = getJuniorDebt()
      this.crud.order.customerName = name;
      this.crud.order.customerCode = code;
      this.crud.order.deptId = deptId;
      this.crud.order.deptName = deptName;
      this.crud.order.auditUserId = userId;
      this.crud.order.auditUserName = userName;
      // this.crud.order.debtAmount = debtAmount;
      this.receiptOrderSelectData = [];
      this.crud.data = [];
      //总应收
      const customerId = this.crud.order.customerId
      const that = this
      getJuniorDebt({customerId: customerId}).then( res=>{
        if (res.status === 200){
          console.log('!!!!!!!!')
          console.log(res.data)
          // setTimeout(()=>{
          //   this.crud.order.debtAmount = res.data
          //   // console.log(this.crud.order.debtAmount)
          //   // this.$message.success(res.msg)
          //   // this.crud.refresh()
          // },3000)
          that.$message.success(res.msg)
          that.crud.order.debtAmount = res.data
          console.log(that.crud.order.debtAmount)
        }else {
          that.$message.error(res.msg)
        }
      })
      this.crud=that.crud
      console.log(that.crud.order.debtAmount)
      this.receiptOrderConfirm();
    }
  },
  destroyed() {
    this.crud.order.bankList = this.bankData;
    this.crud.setItemInfo('financeCustomerReceiptDetail_add');
  }
};
</script>

<style scoped>
.table-img {
  display: inline-block;
  text-align: center;
  background: #ccc;
  color: #fff;
  white-space: nowrap;
  position: relative;
  overflow: hidden;
  vertical-align: middle;
  width: 32px;
  height: 32px;
  line-height: 32px;
}

.handler-div {
  padding-top: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.receipt-order {
  text-align: right;
}
</style>
